package com.lapelife.backend.controller;

import io.swagger.annotations.ApiOperation;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

//@RestController
public class UploadController {
    @PostMapping("/upload")
    @ApiOperation("上传图片")
    public String upload(@RequestParam("file") MultipartFile uploadFile, HttpServletRequest req) throws FileNotFoundException {
        ResourceUtils.getURL("classpath:").getPath();
        SimpleDateFormat sdt = new SimpleDateFormat("yyyyMMdd");
        String format = sdt.format(new Date());
        File folder = Paths.get("D:\\Users\\Mir.Lliao\\Desktop\\course-2023\\JAVAEE企业级应用\\post-read\\backend\\src\\main\\resources\\static\\upload", format).toFile();
        String filePath = "";
        if (!folder.exists() || !folder.isDirectory()) {
            folder.mkdirs();
        }
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            uploadFile.transferTo(new File(folder, newName));
            filePath = req.getScheme() + "://" + req.getServerName() + ":" +
                    req.getServerPort() + "/download/" + format +"/"+ newName;
            System.out.println("filePath = " + filePath);
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败! ";
        }
        return filePath;
    }

    @GetMapping("/download/{dir}/{path}")
    @ApiOperation("图片下载")
    public File download(HttpServletResponse response, @PathVariable String path, @PathVariable String dir) throws IOException {
        path = Paths.get("D:\\Users\\Mir.Lliao\\Desktop\\course-2023\\JAVAEE企业级应用\\post-read\\backend\\src\\main\\resources\\static\\upload\\" + dir, path).toString();
        // if (StringUtils.isNotBlank(path)) {
        //     response.setContentType("image/png");
        //
        //     FileInputStream fileInputStream = new FileInputStream(path);
        //     ServletOutputStream outputStream = response.getOutputStream();
        //
        //     int len;
        //     byte[] bs = new byte[1024];
        //     while ((len = fileInputStream.read(bs)) != -1) {
        //         outputStream.write(bs, 0, len);
        //         outputStream.flush();
        //     }
        //
        //     outputStream.close();
        //     fileInputStream.close();
        // } else {
        //     response.setStatus(500);
        // }
        return new File(path);
    }
}
